<?php

namespace mpend\modules\activity\models;

use Yii;
use mpend\models\User;
use common\models\activity\ActivityEnroll;
use common\validators\MobileValidator;
use common\validators\IdcardValidator;

class ActivityEnrollForm extends \common\base\Model {

    /**
     * @var string 
     */
    public $activity_id;

    /**
     * @var string 
     */
    public $user_id;

    /**
     * @var string 姓名
     */
    public $realname;

    /**
     * @var string 姓名
     */
    public $idcardno;

    /**
     * @var string 姓名
     */
    public $mobile;

    /**
     * @var string 会员号
     */
    public $lntsno;

    /**
     * @var string 会员号
     */
    public $cardno;

    /**
     * @var string 注册类型
     */
    public $paymode;

    /**
     * @var User|null 用户信息
     */
    private $_user;

    /**
     * @var ActivityView|null 活动信息
     */
    private $_activity;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['activity_id', 'user_id'], 'integer'],
            [['realname', 'idcardno', 'mobile', 'paymode'], 'required'],
            [['realname', 'lntsno', 'cardno', 'paymode'], 'string', 'max' => 50],
            [['idcardno'], 'string', 'max' => 18],
            [['mobile'], 'string', 'max' => 11],
            [['user_id'], 'validateUser'],
            [['activity_id'], 'validateActivity'],
            [['mobile'], 'validateMobile'],
            [['idcardno'], 'validateIdcardno'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'name' => '姓名',
            'lntsno' => '成员注册号',
            'cardno' => '会员卡号',
            'mobile' => '手机号',
            'idcardno' => '身份证号',
            'paymode' => '缴费方式',
        ];
    }

    /**
     * 校验唯一手机号
     */
    public function validateMobile($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $validator = new MobileValidator();
        if (!$validator->validate($this->$attribute)) {
            return $this->addError($attribute, '手机号码格式不正确，请输入正确的手机号码！');
        }
    }

    /**
     * 校验唯一身份证号
     */
    public function validateIdcardno($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $validator = new IdcardValidator();
        if (!$validator->validate($this->$attribute)) {
            return $this->addError($attribute, '身份证号码不正确，请输入正确的身份证号码！');
        }
    }

    /**
     * 校验唯一手机号
     */
    public function validateUser($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $userClass = Yii::$app->user->identityClass;
        $user = $userClass::findIdentity($this->$attribute);
        if (!$user) {
            return $this->addError($attribute, '请登录后提交报名信息');
        }
        $this->_user = $user;
    }

    /**
     * 校验唯一手机号
     */
    public function validateActivity($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $activity = ActivityView::findOne($this->$attribute);
        if ($activity->mineEnroll) {
            return $this->addError($attribute, '您已报名了当前活动，无需重复报名');
        }
        if (!$activity->getCanEnroll()) {
            return $this->addError($attribute, '当前活动暂不可以进行报名');
        }
        $this->_activity = $activity;
    }

    /**
     * @return User
     */
    public function getUser() {
        return $this->_user;
    }

    /**
     * 保存动态信息（发布&修改）
     * @param [type] $data
     * @return void
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('');
        }
        $user = $this->getUser();
        $activity = $this->_activity;
        $model = ActivityEnroll::findOrNew([
            'user_id' => $user->id,
            'activity_id' => $activity->id,
        ]);
        $model->setAttributes([
            'realname' => $this->realname,
            'idcardno' => $this->idcardno,
            'mobile' => $this->mobile,
            'lntsno' => $this->lntsno,
            'cardno' => $this->cardno,
            'paymode' => $this->paymode == '微信' ? 'wechat' : 'alipay',
        ]);
        //开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                return $this->dumpError('报名信息保存失败');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->dumpError($e->getMessage());
        }
        return $model;
    }

}
